package com.knowledge.plus.io.AIO;

import cn.hutool.core.date.DateUtil;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.Future;

/**
 * 客户端实现
 *
 * @author TPF
 * @since 2025/6/4
 */
public class AioClient {
    public static void main(String[] args) throws Exception {
        AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
        Future<Void> connectFuture = client.connect(new InetSocketAddress("localhost", 8080));
        connectFuture.get(); // 等待连接完成

        // 异步发送数据
        ByteBuffer sendBuffer = ByteBuffer.wrap(DateUtil.now().getBytes());
        Future<Integer> writeResult = client.write(sendBuffer);
        writeResult.get(); // 等待发送完成

        // 异步接收响应
        ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
        Future<Integer> readResult = client.read(receiveBuffer);
        readResult.get(); // 等待读取完成

        receiveBuffer.flip();
        System.out.println("收到响应: " + new String(receiveBuffer.array()));
        client.close();
    }
}
